<?php
namespace app\common\services\weixin;

use app\common\components\HttpClient;
use app\models\member\OauthAccessToken;
use \app\common\services\BaseService;

/**
 * Class RequestService 请求基础服务类
 * Author: yanhaoqiang
 * @package app\common\services\weixin
 */
class RequestService extends BaseService {
    private static $app_token = "";
    private static $appid = "";
    private static $app_secret = "";

    private static $url = "https://api.weixin.qq.com/cgi-bin/";

    /**
     * [getAccessToken 获取 access_token]
     * @return bool|mixed
     */
    public static function getAccessToken() {
        $date_now = date("Y-m-d H:i:s");
        $access_token_info = OauthAccessToken::find()->where(['>', 'expired_time', $date_now])->limit(1)->one();
        //存在直接取,不存在再到数据库中查询
        if ($access_token_info) {
            return $access_token_info['access_token'];
        }

        $path = 'token?grant_type=client_credential&appid=' . self::getAppId() . '&secret=' . self::getAppSecret();
        $res = self::send($path);
        if (!$res) {
            return self::_err(self::getLastErrorMsg());
        }

        $model_access_token = new OauthAccessToken();
        $model_access_token->access_token = $res['access_token'];
        $model_access_token->expired_time = date("Y-m-d H:i:s", $res['expires_in'] + time() - 200);
        $model_access_token->created_time = $date_now;
        $model_access_token->save(0);
        return $res['access_token'];
    }

    /**
     * [send ]
     * @param $path
     * @param array $data
     * @param string $method
     * @return bool|mixed
     */
    public static function send($path, $data = [], $method = "GET") {

        $request_url = self::$url . $path;

        if ($method == "POST") {
            $res = HttpClient::post($request_url, $data);
        } else {
            $res = HttpClient::get($request_url, []);
        }

        $ret = @json_decode($res, true);
        if (!$ret || (isset($res['errcode']) && $res['errcode'])) {
            return self::_err($res['errmsg']);
        }
        return $ret;
    }

    /**
     * [setConfig ]
     * @param $appid
     * @param $app_token
     * @param $app_secret
     * @return void
     */
    public static function setConfig($appid, $app_token, $app_secret) {
        self::$appid = $appid;
        self::$app_token = $app_token;
        self::$app_secret = $app_secret;
    }

    /**
     * [getAppId ]
     * @return string
     */
    public static function getAppId() {
        return self::$appid;
    }

    /**
     * [getAppSecret ]
     * @return string
     */
    public static function getAppSecret() {
        return self::$app_secret;
    }

    /**
     * [getAppToken ]
     * @return string
     */
    public static function getAppToken() {
        return self::$app_token;
    }
}